package edu.gatech.geochat;

import java.security.Provider;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;

public class LocationCode implements LocationListener {

	public static String getLatitude(Activity context) {
		Location l = lastLocation;
		if (l == null) {
			Log.d("LocationCode", "Null location for " + context.getClass());
			return "0";
		}
		String lat = String.valueOf(l.getLatitude());
		Log.d("LocationCode", "Read latitude for " + context.getClass() + ": " + lat);
		return lat;
	}
	public static String getLongitude(Activity context) {
		Location l = lastLocation;
		if (l == null) {
			Log.d("LocationCode", "Null location for " + context.getClass());
			return "0";
		}
		String lon = String.valueOf(l.getLongitude());
		Log.d("LocationCode", "Read longitude for " + context.getClass() + ": " + lon);
		return lon;
	}
	
	
	public static void getLocation(Activity context) {
		Log.d("LocationCode", "Load location for " + context.getClass());
		
		LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		
		if (lm == null) {
			Log.d("LocationCode", "LocationManager is null");
			return;
		}
		
		LocationProvider provider = lm.getProvider(LocationManager.GPS_PROVIDER);
		
		if (provider == null) {
			Log.d("LocationCode", "Provider is null");
			return;
		}
		
		
		
		
//		Looper.prepare();
//		
//		lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
//		lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,
//				LocationProvider.AVAILABLE, null, System.currentTimeMillis());
//		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
//		
//		synchronized (locList) {
//			Log.d("LocationCode", "Waiting on location");
//			while (lastLocation == null) {
//				Log.d("LocationCode", "looping");
//				try {
//					Thread.sleep(50);
//				} catch (Exception e) {
//					
//				}
//			}
//		}
//		
//		Log.d("LocationCode", "Done waiting.");
	}
	
	private static final Object locList = new Object();
	
	private static LocationCode listener = new LocationCode();
	private static volatile Location lastLocation;
	
	@Override
	public void onLocationChanged(Location location) {
		lastLocation = location;
		synchronized (locList) {
			locList.notifyAll();
		}
	}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}
